package cn.wolfcode.mq.listener;

import cn.wolfcode.domain.RefundLog;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.service.IOrderInfoService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * @Author: Ruomeng
 * @Date: 2025/2/24
 * @Description : shopseckill
 * @Version: 1.0
 */
@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = MQConstant.INTEGRAL_REFUND_TX_GROUP)
public class IntegralRefundTxMessageListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IOrderInfoService orderInfoService;

    /**
     * 执行本地事务
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            orderInfoService.integralRefundRollback((String) o);
            // 执行成功
            return RocketMQLocalTransactionState.UNKNOWN;
        } catch (Exception e) {
            log.error("[RocketMQ事务消息] 执行本地消息异常", e);
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 检查本地事务状态  当执行本地事务没有返回 commit/rollback 的时候会执行本方法
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("[积分退款事务消息] 检查本地事务状态：{}", JSON.toJSONString(message));
        try {
            // 查询当前订单是否已经变成退款状态
            String orderNo = (String) message.getHeaders().get("orderNo");
            // 基于orderNo查询退款记录，如果已有退款记录 说明退款成功 否则退款失败
            RefundLog refundLog = orderInfoService.selectRefundLogByOrderNo(orderNo);
            if (refundLog != null) {
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

}
